//
//  ZYForwardingMsg.m
//  OC_Principle
//
//  Created by wangzhipan on 2025/2/11.
//

#import "ZYForwardingMsg.h"
#import "ZYCrashGuard.h"

@implementation ZYForwardingMsg

/*
 对象方法:
 1、首先可以在-forwardingTargetForSelector方法中，返回需要统一处理的实例对象
 
 类方法：
 1、首先可以在+forwardingTargetForSelector方法中，返回需要统一处理的类对象
 */

/*
- (id)forwardingTargetForSelector:(SEL)aSelector
{
    if (aSelector == @selector(run)) {
        return [NSClassFromString(@"ZYPerson") new];
    }
    return [super forwardingTargetForSelector:aSelector];
}

+ (id)forwardingTargetForSelector:(SEL)aSelector
{
    if (aSelector == @selector(doSomething)) {
        return NSClassFromString(@"ZYPerson");
    }
    return [super forwardingTargetForSelector:aSelector];
}
 */

/*
 如果forwardingTargetForSelector返回nil的话，那么在方法签名这处理
 methodSignatureForSelector 如果不处理，就会马上抛出找不到方法实现的异常
 */

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
{
    return [NSMethodSignature signatureWithObjCTypes:"v@:#"];
}

+ (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
{
    return [NSMethodSignature signatureWithObjCTypes:"v@:#"];
}

/*
 对象方法处理
 如果methodSignatureForSelector返回了方法签名，那么我们统一在forwardInvocation中处理
 在这里，我们可以自定义任何逻辑
 
 */
- (void)forwardInvocation:(NSInvocation *)anInvocation
{
    //将崩溃信息转发到ZYCrashGuard 中
    NSString *trace = [NSString stringWithFormat:@"%@ not implement -[%s] method", NSStringFromClass([anInvocation.target class]), anInvocation.selector];
    anInvocation.selector = @selector(crashGuard:);
    [anInvocation setArgument:&trace atIndex:2];
    [anInvocation invokeWithTarget:[ZYCrashGuard new]];
}

+ (void)forwardInvocation:(NSInvocation *)anInvocation
{
    NSString *trace = [NSString stringWithFormat:@"%@ not implement +[%s] method", NSStringFromClass([anInvocation.target class]), anInvocation.selector];
    anInvocation.selector = @selector(crashGuard:);
    [anInvocation setArgument:&trace atIndex:2];
    [anInvocation invokeWithTarget:[ZYCrashGuard class]];
}

@end
